//
//  SFStatusViewModel.swift
//  SFWeiBo
//
//  Created by 孙凡 on 16/4/11.
//  Copyright © 2016年 Edward. All rights reserved.
//

import UIKit
import SDWebImage

class SFStatusListViewModel: NSObject {

    
    var statusArray: [SFStatusViewModel]?


    //加载数据
    func loadData(isAnimation: Bool, finished: (error: NSError?)->()){

        //urlString
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"

        var max_id: Int64 = 0
        var sin_id: Int64 = 0
        if isAnimation == true {
            max_id = statusArray?.last?.status?.id ?? 0

            if max_id != 0 {

                max_id = max_id - 1
            }

        }else {

            sin_id = statusArray?.first?.status?.id ?? 0
        }

        //参数
        let paramters :[String: AnyObject] = ["access_token": SFUserAccountViewModel.sharedAccountViewModel.accessToken!,
                                              "max_id": "\(max_id)",

                                              "since_id": "\(sin_id)"]

        //发送请求
        SFNetworkTools.sharedTools.request(SFRequestMethod.GET, URLString: urlString, parameters: paramters) { (responseObjct, error) in

            if error != nil {

                finished(error: error)

                return
            }

//           print(responseObjct)

            //取出一个数组字典(外边是一个数组,里面是字典)
            let dicts = responseObjct!["statuses"] as! [[String: AnyObject]]

            //初始化一个可变模型数组
            var models = [SFStatusViewModel]()

            //遍历取出字典
            for dict in dicts {

                let model = SFStatus(dict: dict)

//                print(model)


                let statusViewModel = SFStatusViewModel(status: model)

                models.append(statusViewModel)
                
            }

            if self.statusArray == nil {

                self.statusArray = [SFStatusViewModel]()
            }

//            print(models.count)
            //拼接数据
            if isAnimation == true {

                self.statusArray! += models

            } else {

                self.statusArray! = models + self.statusArray!
            }

            //回调加载成功
//            finished(error: nil)

            //去缓存一张图的微博图片,用来就算单张图片的计算高度
            self.cacheImageForOnePicture(models, finished: finished)

        }
        
    }


    private func cacheImageForOnePicture(models: [SFStatusViewModel], finished: (error: NSError?)->()){


        let group = dispatch_group_create()

        let mainQueue = dispatch_get_main_queue()

//        weak var mySelf = self

        //取出模型数组中的模型
        for model in models {

            //当原创图片有值

            var urls = model.status?.pic_urls

            //当原创图片的值为空
            if urls == nil || urls!.count == 0  {
                //就变成转发图片的值
                urls = model.status?.retweeted_status?.pic_urls
                //在为空就continue了
                if urls == nil || urls!.count == 0{

                    continue
                }

            }

            //当只有一张图时,进行缓存
            if urls!.count == 1 {


                guard let url = NSURL(string: (urls?.first?.thumbnail_pic)!) else {

                    continue
                }

                dispatch_group_enter(group)

                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, error, _, _, _) in

                    if error != nil {

                        print(error)
                    }

                    dispatch_group_leave(group)
                })

            }

        }

        dispatch_group_notify(group, mainQueue) { 

            finished(error: nil)
        }


    }
    

}
